<template>
  <div class="calendar-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>农事日历管理</h2>
          <!-- <el-button type="primary" @click="showAddDialog" style="background-color: #5a8a5c;">添加农事</el-button> -->
        </div>
      </template>

      <el-calendar v-model="currentDate">
        <template #date-cell="{ data }">
          <div class="calendar-day" @click="handleDateClick(data.day)">
            <div class="day-number">{{ data.day.split('-')[2] }}</div>
            <div class="events-container">
              <el-tag
                v-for="event in getEventsForDay(data.day)"
                :key="event.id"
                :type="getEventTagType(event.type)"
                size="small"
                class="event-tag"
                @click.stop="showEventDetail(event)"
              >
                {{ event.title }}
              </el-tag>
            </div>
          </div>
        </template>
      </el-calendar>
    </el-card>

    <!-- 添加/编辑农事对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditing ? '编辑农事' : '添加农事'"
      width="600px"
    >
      <el-form :model="eventForm" label-width="100px">
        <el-form-item label="农事名称" required>
          <el-input v-model="eventForm.title" placeholder="请输入农事名称" />
        </el-form-item>
        <el-form-item label="农田区域" required>
          <el-select v-model="eventForm.fieldId" placeholder="请选择农田区域">
            <el-option
              v-for="field in fields"
              :key="field.id"
              :label="field.name"
              :value="field.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="日期" required>
          <el-date-picker
            v-model="eventForm.date"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="时间" required>
          <el-time-picker
            v-model="eventForm.time"
            placeholder="选择时间"
            format="HH:mm"
            value-format="HH:mm"
          />
        </el-form-item>
        <el-form-item label="农事类型" required>
          <el-select v-model="eventForm.type" placeholder="请选择农事类型">
            <el-option
              v-for="type in eventTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" required>
          <el-select v-model="eventForm.status" placeholder="请选择状态">
            <el-option
              v-for="(label, value) in statusText"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="详细描述">
          <el-input
            v-model="eventForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入详细描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEventForm">
            {{ isEditing ? '更新' : '添加' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 农事详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="农事详情" width="500px">
      <div class="event-detail">
        <h3>{{ currentEvent.title }}</h3>
        <div class="detail-item">
          <span class="label">农田区域：</span>
          <span>{{ getFieldName(currentEvent.fieldId) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">时间：</span>
          <span>{{ currentEvent.date }} {{ currentEvent.time }}</span>
        </div>
        <div class="detail-item">
          <span class="label">类型：</span>
          <el-tag :type="getEventTagType(currentEvent.type)">
            {{ getEventTypeLabel(currentEvent.type) }}
          </el-tag>
        </div>
        <div class="detail-item">
          <span class="label">状态：</span>
          <el-tag :type="getStatusTagType(currentEvent.status)">
            {{ statusText[currentEvent.status] }}
          </el-tag>
        </div>
        <div class="detail-item">
          <span class="label">描述：</span>
          <p>{{ currentEvent.description }}</p>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="editCurrentEvent">编辑</el-button>
          <el-button type="danger" @click="deleteCurrentEvent">删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const currentDate = ref(new Date())
const events = ref([])
const fields = ref([])
const eventTypes = ref([])
const statusText = ref({})

// 对话框控制
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const isEditing = ref(false)

// 表单数据
const eventForm = ref({
  id: '',
  title: '',
  fieldId: '',
  date: '',
  time: '',
  type: '',
  status: 'pending',
  description: ''
})

// 当前选中的事件
const currentEvent = ref({})

// 获取某天的事件
const getEventsForDay = (date) => {
  return events.value.filter(event => event.date === date)
}

// 获取农田名称
const getFieldName = (fieldId) => {
  const field = fields.value.find(f => f.id == fieldId)
  return field ? field.name : '未知农田'
}

// 获取事件类型标签
const getEventTypeLabel = (type) => {
  const eventType = eventTypes.value.find(t => t.value === type)
  return eventType ? eventType.label : type
}

// 获取标签类型
const getEventTagType = (type) => {
  switch (type) {
    case 'fertilize': return 'warning'
    case 'water': return 'primary'
    case 'weed': return 'success'
    case 'pest': return 'danger'
    case 'harvest': return ''
    default: return 'info'
  }
}

const getStatusTagType = (status) => {
  switch (status) {
    case 'pending': return 'warning'
    case 'completed': return 'success'
    case 'overdue': return 'danger'
    default: return 'info'
  }
}

// 日期点击事件
const handleDateClick = (date) => {
  const events = getEventsForDay(date)
  if (events.length > 0) {
    currentEvent.value = events[0]
    detailDialogVisible.value = true
  }
}

// 显示添加对话框
const showAddDialog = () => {
  isEditing.value = false
  eventForm.value = {
    id: '',
    title: '',
    fieldId: fields.value[0]?.id || '',
    date: formatDate(new Date()),
    time: formatTime(new Date()),
    type: eventTypes.value[0]?.value || '',
    status: 'pending',
    description: ''
  }
  dialogVisible.value = true
}

// 显示事件详情
const showEventDetail = (event) => {
  currentEvent.value = event
  detailDialogVisible.value = true
}

// 编辑当前事件
const editCurrentEvent = () => {
  isEditing.value = true
  eventForm.value = { ...currentEvent.value }
  dialogVisible.value = true
  detailDialogVisible.value = false
}

// 删除当前事件
const deleteCurrentEvent = () => {
  ElMessageBox.confirm('确定要删除这条农事记录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteEvent(currentEvent.value.id)
    detailDialogVisible.value = false
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// 提交表单
const submitEventForm = () => {
  if (!eventForm.value.title || !eventForm.value.fieldId || 
      !eventForm.value.date || !eventForm.value.time || 
      !eventForm.value.type) {
    ElMessage.warning('请填写完整信息')
    return
  }

  if (isEditing.value) {
    updateEvent(eventForm.value)
  } else {
    addEvent(eventForm.value)
  }
  dialogVisible.value = false
}

// 日期格式化
const formatDate = (date) => {
  const d = new Date(date)
  return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`
}

const formatTime = (date) => {
  const d = new Date(date)
  return `${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}`
}

// API 请求
const fetchData = async () => {
  try {
    const [eventsRes, fieldsRes, typesRes, statusRes] = await Promise.all([
      fetch('http://localhost:3000/events').then(res => res.json()),
      fetch('http://localhost:3000/fields').then(res => res.json()),
      fetch('http://localhost:3000/eventTypes').then(res => res.json()),
      fetch('http://localhost:3000/statusText').then(res => res.json())
    ])
    
    events.value = eventsRes
    fields.value = fieldsRes
    eventTypes.value = typesRes
    statusText.value = statusRes
  } catch (error) {
    console.error('获取数据失败:', error)
  }
}

const addEvent = async (event) => {
  try {
    const response = await fetch('http://localhost:3000/events', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        ...event,
        id: Date.now().toString()
      })
    })
    const newEvent = await response.json()
    events.value.push(newEvent)
    ElMessage.success('添加成功')
  } catch (error) {
    console.error('添加失败:', error)
    ElMessage.error('添加失败')
  }
}

const updateEvent = async (event) => {
  try {
    const response = await fetch(`http://localhost:3000/events/${event.id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(event)
    })
    const updatedEvent = await response.json()
    const index = events.value.findIndex(e => e.id === updatedEvent.id)
    if (index !== -1) {
      events.value[index] = updatedEvent
    }
    ElMessage.success('更新成功')
  } catch (error) {
    console.error('更新失败:', error)
    ElMessage.error('更新失败')
  }
}

const deleteEvent = async (id) => {
  try {
    await fetch(`http://localhost:3000/events/${id}`, {
      method: 'DELETE'
    })
    events.value = events.value.filter(event => event.id !== id)
    ElMessage.success('删除成功')
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.calendar-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.calendar-day {
  height: 100%;
  padding: 8px;
  box-sizing: border-box;
}

.day-number {
  font-weight: bold;
  margin-bottom: 4px;
}

.events-container {
  max-height: 80px;
  overflow-y: auto;
}

.event-tag {
  margin: 2px;
  cursor: pointer;
}

.event-detail {
  padding: 10px;
}

.detail-item {
  margin-bottom: 15px;
}

.detail-item .label {
  font-weight: bold;
  color: #666;
}

.el-calendar {
  border-radius: 4px;
}

.el-calendar :deep(.el-calendar__header) {
  padding: 12px 20px;
}

.el-calendar :deep(.el-calendar__body) {
  padding: 12px 20px 35px;
}
</style>